package com.ruoyi.system.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RoleUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 产值Controller
 * 
 * @author xuliang
 * @date 2024-04-05
 */
@RestController
@RequestMapping("/system/output")
@Slf4j
public class OutputController extends BaseController
{
    @Autowired
    private IProjectInfoService projectInfoService;
    @Autowired
    private IProcurementDetailService procurementDetailService;
    @Autowired
    private ILaborService laborService;
    @Autowired
    private IDirectService directService;
    @Autowired
    private IIndirectService indirectService;
    @Autowired
    private IOutputService outputService;

    /**
     * 查询产值列表
     */
    @PreAuthorize("@ss.hasPermi('system:output:list')")
    @GetMapping("/list")
    public Map<String,Object> list(Output output)
    {

        if(!RoleUtils.hasPermission(projectInfoService.getRoleIdsByUserId(getUserId()))){
            output.setProjectCode(projectInfoService.getProjectCodeByUserId(getUserId()));
        }else {
            output.setProjectCode(null);
        }

        startPage();
        List<Output> outputList = outputService.selectOutputList(output);

        List<String> projectCodeList = projectInfoService.getProjectCodes(output.getAreaId());

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("projectCodeList",projectCodeList);
        dataMap.put("dataList",getDataTable(outputList));

        return dataMap;
    }

    /**
     * 导出产值列表
     */
    @PreAuthorize("@ss.hasPermi('system:output:export')")
    @Log(title = "产值", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Output output)
    {
        List<Output> list = outputService.selectOutputList(output);
        ExcelUtil<Output> util = new ExcelUtil<Output>(Output.class);
        util.exportExcel(response, list, "产值数据");
    }

    /**
     * 获取产值详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:output:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(outputService.selectOutputById(id));
    }

    /**
     * 新增产值
     */
    @PreAuthorize("@ss.hasPermi('system:output:add')")
    @Log(title = "产值", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Output output)
    {
        output.calculateTax();
        output.setProjectCode(projectInfoService.getProjectCodeByUserId(getUserId()));
        output.setCreateBy(getUsername());
        output.setCreateTime(DateUtils.getNowDate());

        if(outputService.checkOutputByCodeAndDateNumber(output.getProjectCode(),output.getDateNumber()) != 0){
            return error("已存在同期产值，请对同期产值进行修改操作或添加新一期产值");
        }

        projectInfoService.updateProjectNumber(DateUtils.getMonth(),output.getProjectCode());

        ProjectInfo query = new ProjectInfo();
        query.setProjectCode(output.getProjectCode());

        ProjectInfo projectInfo = projectInfoService.selectProjectInfo(query);

        output.setProjectName(projectInfo.getProjectName());

        return toAjax(outputService.insertOutput(output));
    }

    /**
     * 修改产值
     */
    @PreAuthorize("@ss.hasPermi('system:output:edit')")
    @Log(title = "产值", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Output output)
    {
        output.calculateTax();
        output.setUpdateBy(getUsername());
        output.setUpdateTime(DateUtils.getNowDate());

        ProjectInfo query = new ProjectInfo();
        query.setProjectCode(output.getProjectCode());

        ProjectInfo projectInfo = projectInfoService.selectProjectInfo(query);

        String name = projectInfo.getProjectName();
        output.setProjectName(name);

        return toAjax(outputService.updateOutput(output));
    }

    /**
     * 删除产值
     */
    @PreAuthorize("@ss.hasPermi('system:output:remove')")
    @Log(title = "产值", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(outputService.deleteOutputByIds(ids));
    }

    /**
     * 上传附件
     */
    @PreAuthorize("@ss.hasPermi('system:output:upload')")
    @Log(title = "产值", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file")MultipartFile file,@RequestParam("id") long id) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("上传的文件为空");
        }

        try {
            String relativePath = "uploadFile/output";
            String uploadDir = System.getProperty("user.dir") + File.separator + relativePath;

            // 如果目录不存在，创建目录
            File dir = new File(uploadDir);

            if(!dir.exists()){
                dir.mkdirs();
            }

            // 构造文件路径
            String filePath = uploadDir + File.separator + file.getOriginalFilename();

            // 将上传文件复制到指定路径
            FileCopyUtils.copy(file.getBytes(),new File(filePath));

            Output output = new Output();
            output.setUpdateBy(getUsername());
            output.setUpdateTime(DateUtils.getNowDate());
            output.setId(id);
            output.setRemark(relativePath + File.separator + file.getOriginalFilename());

            outputService.updateOutput(output);

            ProjectInfo query = new ProjectInfo();
            query.setProjectCode(output.getProjectCode());

            return success("文件上传成功");
        } catch (IOException e) {
            return error("文件上传失败");
        }


    }

}
